package com.gzxw.mogublog.xo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gzxw.mogublog.base.global.BaseSysConf;
import com.gzxw.mogublog.commons.entity.SysDicData;
import com.gzxw.mogublog.commons.entity.SysDicType;
import com.gzxw.mogublog.utils.JsonUtils;
import com.gzxw.mogublog.utils.R;
import com.gzxw.mogublog.utils.RedisUtil;
import com.gzxw.mogublog.xo.mapper.SysDicDataMapper;
import com.gzxw.mogublog.xo.service.SysDicDataService;
import com.gzxw.mogublog.xo.service.SysDicTypeService;
import com.gzxw.mogublog.xo.vo.SysDictDataVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class SysDicDataServiceImpl extends ServiceImpl<SysDicDataMapper, SysDicData> implements SysDicDataService {

    @Autowired
    private SysDicTypeService sysDictTypeService;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public IPage<SysDicData> getList(SysDictDataVO sysDictDataVO) {
        QueryWrapper<SysDicData> queryWrapper = new QueryWrapper<>();
        // 字典类型UID
        if (StringUtils.isNotEmpty(sysDictDataVO.getDictTypeUid())) {
            queryWrapper.eq("dict_type_uid", sysDictDataVO.getDictTypeUid());
        }
        // 字典标签
        if (StringUtils.isNotEmpty(sysDictDataVO.getDictLabel()) && !StringUtils.isEmpty(sysDictDataVO.getDictLabel().trim())) {
            queryWrapper.like("dict_label", sysDictDataVO.getDictLabel().trim());
        }
        Page<SysDicData> page = new Page<>();
        page.setCurrent(sysDictDataVO.getCurrentPage());
        page.setSize(sysDictDataVO.getPageSize());
        queryWrapper.eq("status", 1);
        queryWrapper.orderByDesc("sort", "create_time");
        IPage<SysDicData> pageList = this.page(page, queryWrapper);
        List<SysDicData> sysDictDataList = pageList.getRecords();
        Set<String> dictTypeUidList = new HashSet<>();
        sysDictDataList.forEach(item -> {
            dictTypeUidList.add(item.getDictTypeUid());
        });
        Collection<SysDicType> dictTypeList = new ArrayList<>();
        if (dictTypeUidList.size() > 0) {
            dictTypeList = sysDictTypeService.listByIds(dictTypeUidList);
        }
        Map<String, SysDicType> dictTypeMap = new HashMap<>();
        dictTypeList.forEach(item -> {
            dictTypeMap.put(item.getUid(), item);
        });
        sysDictDataList.forEach(item -> {
            item.setSysDictType(dictTypeMap.get(item.getDictTypeUid()));
        });
        pageList.setRecords(sysDictDataList);
        return pageList;
    }

    @Override
    public String addSysDictData(SysDictDataVO sysDictDataVO) {
        // 判断当前添加的是否存在
        QueryWrapper<SysDicData> sysDicDataQueryWrapper = new QueryWrapper<>();
        sysDicDataQueryWrapper.eq("status", 1);
        sysDicDataQueryWrapper.eq("dict_label", sysDictDataVO.getDictLabel().trim());
        sysDicDataQueryWrapper.eq("dict_type_uid", sysDictDataVO.getDictTypeUid());
        int count = this.count(sysDicDataQueryWrapper);
        if (count > 0) {
            return "该实体已经存在";
        }
        SysDicData sysDicData = new SysDicData();
        BeanUtils.copyProperties(sysDictDataVO, sysDicData, "status");
        sysDicData.setCreateByUid("admin");
        sysDicData.setUpdateByUid("admin");
        this.save(sysDicData);
        return "插入成功";
    }

    @Override
    public String editDicData(SysDictDataVO sysDictDataVO) {

        // 判断当前编辑的字典数据是否存在
        QueryWrapper<SysDicData> sysDicDataQueryWrapper = new QueryWrapper<>();
        sysDicDataQueryWrapper.eq("status", 1);
        sysDicDataQueryWrapper.eq("dict_type_uid", sysDictDataVO.getDictTypeUid());
        sysDicDataQueryWrapper.eq("dict_label", sysDictDataVO.getDictLabel().trim());
        int count = this.count(sysDicDataQueryWrapper);
        if (count > 0) {
            return "编辑的字典已经存在";
        }
        // 从数据库中获取
        SysDicData sysDicData = this.getById(sysDictDataVO.getUid());
        // 更新数据字典【使用Spring工具类提供的深拷贝，避免出现大量模板代码】
        BeanUtils.copyProperties(sysDictDataVO, sysDicData, "status", "uid");
        sysDicData.setUpdateTime(new Date());
        sysDicData.setUpdateByUid("admin");
        this.updateById(sysDicData);
        return "更新成功";
    }

    @Override
    public String deleteBatch(List<SysDictDataVO> sysDictDataVOList) {

        if (sysDictDataVOList.size() <= 0) {
            return "参数有误!";
        }
        List<String> uids = new ArrayList<>();
        sysDictDataVOList.forEach(item -> {
            uids.add(item.getUid());
        });
        Collection<SysDicData> sysDicDataCollection = this.listByIds(uids);
        sysDicDataCollection.forEach(item -> {
            item.setUpdateTime(new Date());
            item.setStatus(0);
        });
        this.updateBatchById(sysDicDataCollection);
        // redis中删除
        return "删除成功";
    }

    @Override
    public Map<String, Object> getListByDictType(String dictType) {

        QueryWrapper<SysDicType> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dict_type", dictType);
        queryWrapper.eq("status", 1);
        queryWrapper.eq("is_publish", 1);
        queryWrapper.last("limit 1");
        SysDicType sysDictType = sysDictTypeService.getOne(queryWrapper);
        if (sysDictType == null) {
            return new HashMap<>();
        }
        QueryWrapper<SysDicData> sysDictDataQueryWrapper = new QueryWrapper<>();
        sysDictDataQueryWrapper.eq("is_publish", 1);
        sysDictDataQueryWrapper.eq("status", 1);
        sysDictDataQueryWrapper.eq("dict_type_uid", sysDictType.getUid());
        sysDictDataQueryWrapper.orderByDesc("sort", "create_time");
        List<SysDicData> list = this.list(sysDictDataQueryWrapper);
        Map<String, Object> result = new HashMap<>();
        result.put("list", list);
        // TODO redis操作
        return result;
    }

    @Override
    public Map<String, Object> getListByDictTypeList(List<String> sysDicDataList) {
        // 先从redis中获取
        Map<String, Object> result = new HashMap<>();
        List<String> dictTypeUids = new ArrayList<>();

        // 此处需要判断数据是否全部从redis中获取到了
        List<String > noGetDictTypes = new ArrayList<>();
        sysDicDataList.forEach(item -> {

            String jsonResult = redisUtil.get(BaseSysConf.REDIS_DICT_TYPE + BaseSysConf.REDIS_SEGMENTATION + item);
            //判断redis中是否有字典
            if (StringUtils.isNotEmpty(jsonResult)) {
                List<SysDicData> sysDicDatas = JsonUtils.jsonToList(jsonResult, SysDicData.class);
                result.put(item,sysDicDatas);
            }else {
                // 如果没有，则放入未查到的Redis数据列表
                noGetDictTypes.add(item);
            }
        });

        // 如果noGetDictTypes的size小于等于0，说明全都在redis中获取到了
        if (noGetDictTypes.size()<=0) {
            return result;
        }

        QueryWrapper<SysDicType> sysDicTypeQueryWrapper = new QueryWrapper<>();
        sysDicTypeQueryWrapper.eq("status", 1);
        sysDicTypeQueryWrapper.eq("is_publish", 1);
        sysDicTypeQueryWrapper.orderByDesc("sort");
        sysDicTypeQueryWrapper.in("dict_type",noGetDictTypes);
        List<SysDicType> dictTypeList = sysDictTypeService.list(sysDicTypeQueryWrapper);
        Map<String ,String > map = new HashMap<>();
        dictTypeList.forEach(item -> {
            map.put(item.getUid(),item.getDictType());
            dictTypeUids.add(item.getUid());
        });

        dictTypeUids.forEach(item -> {
            Map<String, Object> redisResult = new HashMap<>();
            QueryWrapper<SysDicData> sysDicDataQueryWrapper = new QueryWrapper<>();
            sysDicDataQueryWrapper.eq("status",1);
            sysDicDataQueryWrapper.eq("is_publish",1);
            sysDicDataQueryWrapper.eq("dict_type_uid",item);
            List<SysDicData> dicDataList = this.list(sysDicDataQueryWrapper);
            // 将该类型字典列表存入redis中
            redisUtil.setEx(BaseSysConf.REDIS_DICT_TYPE+BaseSysConf.REDIS_SEGMENTATION+map.get(item),JsonUtils.objectToJson(dicDataList).toString(),1,TimeUnit.DAYS);
            result.put(map.get(item),dicDataList);
        });
        return result;
    }
}
